package com.attack.controller;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.attack.api.utils.BaseRedisService;
import com.attack.entity.AppEntity;
import com.attack.mapper.AppMapper;
import com.attack.utils.BaseApiService;
import com.attack.utils.ResponseBase;
import com.attack.utils.TokenUtils;

@RestController
@RequestMapping("/auth")
public class TokenAccessController  extends BaseApiService{
	@Autowired
	private  AppMapper appMapper;
	@Autowired
	private BaseRedisService baseRedisService;
	
	private final static long timeToken=60*60*2;
	/**
	 * 生成token
	 * @return
	 */
	@RequestMapping("/getToken")
	public ResponseBase  getToken(AppEntity appEntity){
		AppEntity app=appMapper.findApp(appEntity);
		if(app==null){
			return setResultError("没有查询到对应的组织机构!");
		}
		if(app.getIsFlag()==1){
			return setResultError("对应的组织机构已经失效!");
		}
		if(app.getAccessToken()!=null){
			baseRedisService.delKey(app.getAccessToken());
		}
		// 生成的新的accessToken
		String newAccessToken = newAccessToken(app.getAppId());
		appMapper.updateAccessToken(newAccessToken, app.getAppId());
		baseRedisService.setString(newAccessToken, app.getAppId(), timeToken);
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("accessToken", newAccessToken);
		return setResultSuccessData(jsonObject);
	}
	@RequestMapping("/findApi")
	public ResponseBase findApi(String accessToken){
	/*	if(StringUtils.isEmpty(accessToken)){
			return setResultError("accessToken 不能为空!");
		}
		String redisResult=(String) baseRedisService.getString(accessToken);
		if(StringUtils.isEmpty(redisResult)){
			return setResultError("accessToken 无效!");
		}*/
		//使用拦截器拦截处理
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("result", "api接口调用成功了。。。");
		return setResultSuccessData(jsonObject);
		
	}
	
	
	private String newAccessToken(String appId) {
		// 使用appid+appsecret 生成对应的AccessToken 保存两个小时
		String accessToken = TokenUtils.getAccessToken();
		// 保证在同一个事物redis 事物中
		// 生成最新的token key为accessToken value 为 appid
		baseRedisService.setString(accessToken, appId, timeToken);
		// 表中保存当前accessToken
		appMapper.updateAccessToken(accessToken, appId);
		return accessToken;
	}


}
